package com.luck.easyfoodbatch;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.EMLog;
import com.igexin.sdk.PushManager;
import com.luck.easyfoodbatch.custom.AutoUpdateManager;
import com.luck.easyfoodbatch.db.FindDB;
import com.luck.easyfoodbatch.db.MessageDB;
import com.luck.easyfoodbatch.db.PlaceDB;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.dialog.SVProgressHUD;
import com.luck.easyfoodbatch.fragment.CategoryFragment;
import com.luck.easyfoodbatch.fragment.FindFragment;
import com.luck.easyfoodbatch.fragment.HomeFragment;
import com.luck.easyfoodbatch.fragment.MineFragment;
import com.luck.easyfoodbatch.fragment.ShopCardFragment;
import com.luck.easyfoodbatch.mvp.home.CountryModel;
import com.luck.easyfoodbatch.mvp.home.CountryPresenter;
import com.luck.easyfoodbatch.mvp.home.CountryView;
import com.luck.easyfoodbatch.mvp.model.Country;
import com.luck.easyfoodbatch.ui.BaseNoSliderActivity;
import com.luck.easyfoodbatch.ui.ChatActivity;
import com.luck.easyfoodbatch.ui.LocationActivity;
import com.luck.easyfoodbatch.ui.LoginActivity;
import com.luck.easyfoodbatch.ui.MessageActivity;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;

public class MainActivity extends BaseNoSliderActivity implements CountryView {
    protected static final String TAG = "MainActivity";
    @BindView(R.id.tab_content)
    FrameLayout tabContent;
    //    @BindView(R.id.tv_home)
//    TextView tvHome;
    @BindView(R.id.ll_container_home)
    LinearLayout ll_container_home;
    //    @BindView(R.id.tv_category)
//    TextView tvCategory;
    @BindView(R.id.ll_container_category)
    LinearLayout llContainerCategory;
    //    @BindView(R.id.tv_find)
//    TextView tvFind;
    @BindView(R.id.ll_container_find)
    LinearLayout llContainerFind;
    //    @BindView(R.id.tv_shop)
//    TextView tvShop;
    @BindView(R.id.ll_container_shop)
    LinearLayout llContainerShop;
    //    @BindView(R.id.tv_me)
//    TextView tvMe;
    @BindView(R.id.unread_msg_number)
    TextView unreadMsgNumber;
    @BindView(R.id.rl_container_me)
    RelativeLayout rlContainerMe;
    @BindView(R.id.iv_home)
    ImageView iv_home;
    @BindView(R.id.iv_category)
    ImageView ivCategory;
    @BindView(R.id.iv_find)
    ImageView ivFind;
    @BindView(R.id.iv_shop)
    ImageView ivShop;
    @BindView(R.id.iv_mine)
    ImageView ivMine;
    private SVProgressHUD pd;
    private Fragment[] fragments;
    //    private TextView[] mTabs;
    private ImageView[] views;
    // 当前fragment的index
    private int currentTabIndex;
    private int index;
    private int type = 0;
    private HomeFragment homeFragment;
        private CategoryFragment categoryFragment;
    private FindFragment findFragment;
//    private CategoryFragmentCopy categoryFragment;
    private ShopCardFragment cardFragment;
    private MineFragment mineFragment;
    private boolean isExceptionDialogShow = false;
    // user logged into another device
    public boolean isConflict = false;
    // user account was removed
    private boolean isCurrentAccountRemoved = false;
    private BroadcastReceiver internalDebugReceiver;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;
    private FindDB findDB;
    public LocationClient mLocClient;
    private PlaceDB placeDB;
    private CountryModel countryModel;
    private AutoUpdateManager mAutoUpdateManager;
    public MyLocationListenner myListener = new MyLocationListenner();
    public BDLocation lastLocation = null;
    private MessageDB messageDB;
    private Handler mHander = new Handler();
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.logout")) {
                // 注销登录广播
                showTab(0);
                onCheckedIndex(0);
                if (homeFragment != null) {
                    homeFragment.initMessage(0);
                }
            } else if (intent.getAction().equals("action.app.main")) {
                showTab(0);
                onCheckedIndex(0);
            } else if (intent.getAction().equals("action.app.cart.refresh")) {
                //刷新购物车列表
                if (cardFragment != null) {
                    cardFragment.onRefreshCart();
                }
            } else if (intent.getAction().equals("action.app.cart")) {
                // 进入购物车
                index = 3;
                FragmentTransaction trx = obtainFragmentTransaction(index);
                trx.hide(fragments[currentTabIndex]);
                if (!fragments[index].isAdded()) {
                    trx.add(R.id.tab_content, fragments[index]);
                }
                trx.show(fragments[index]).commitAllowingStateLoss();
//                mTabs[currentTabIndex].setSelected(false);
                views[currentTabIndex].setSelected(false);
                // 把当前tab设为选中状态
//                mTabs[index].setSelected(true);
                views[index].setSelected(true);
                currentTabIndex = index;
            } else if (intent.getAction().equals("action.refreshMessage")) {
                // 新消息(系统消息，非聊天)
                if (isCheckedLogin()) {
                    if (homeFragment != null) {
                        homeFragment.initMessage(1);
                    }
                }
            } else if (intent.getAction().equals("action.app.refresh.mine")) {
                if (isCheckedLogin()) {
                    if (mineFragment != null) {
                        mHander.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mineFragment.initMessage();
                            }
                        }, 500);
                    }
                }
            } else if (intent.getAction().equals("app.action.refresh.location")) {
                // 定位
                if (homeFragment != null) {
                    homeFragment.initCity();
                }

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //检查版本更新
        pd = new SVProgressHUD(MainActivity.this);
        mAutoUpdateManager = new AutoUpdateManager(mContext);
        mAutoUpdateManager.updateVersion();

        String p_id = (String) SharedPreferencesUtil.getData(MainActivity.this, HttpUtil.P_ID, "");
        if (Tools.isNull(p_id)) {
            // 没有选择过定位地址
            startAct(LocationActivity.class);
        }
        setContentView(R.layout.activity_main);
        messageDB = new MessageDB(this);
        type = getIntent().getIntExtra("type", 0);
        //make sure activity will not in background if user is logged into another device or removed
        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
            DemoHelper.getInstance().logout(false, null);
            startActivity(new Intent(this, LoginActivity.class));
            App.getInstance().saveObject(null, HttpUtil.USER_KEY);
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            startActivity(new Intent(this, LoginActivity.class));
            App.getInstance().saveObject(null, HttpUtil.USER_KEY);
            return;
        }

        ButterKnife.bind(this);
        findDB = new FindDB(this);
        placeDB = new PlaceDB(this);
        registerReceiver(receiver, "action.app.logout", "action.app.cart.refresh", "app.action.refresh.location", "action.app.main", "action.app.cart", "action.refreshMessage", "action.app.refresh.mine");
        initViews();
        initFragment();

        showExceptionDialogFromIntent(getIntent());
        EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
        registerBroadcastReceiver();
        PushManager.getInstance().initialize(this);
        ShareSDK.initSDK(this);
        // 后台点击通知栏消息时，延迟1秒启动，在跳转 防止一进来页面空白一下
        mHander.postDelayed(new Runnable() {
            @Override
            public void run() {
                countryModel = new CountryPresenter(MainActivity.this, mContext);
                countryModel.getCountryList(1);
                notificationActivity(type);
            }
        }, 1200);

        //showMapWithLocationClient();
    }


    /**
     * 通知栏点击 启动相应的Activity
     */
    private void notificationActivity(int type) {
        if (type == 0) {
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (type) {
            case 1:
                // 系统消息
                intent.setClass(mContext, MessageActivity.class);
                break;
            case 2:
                // 订单消息
                intent.setClass(mContext, MessageActivity.class);
                break;
        }
        bundle.putInt("currIndex", 1);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        homeFragment = new HomeFragment();
        categoryFragment = new CategoryFragment();
        findFragment = new FindFragment();
        cardFragment = new ShopCardFragment();
        mineFragment = new MineFragment();
        fragments = new Fragment[]{homeFragment, categoryFragment, findFragment, cardFragment, mineFragment};
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction().add(R.id.tab_content, homeFragment).add(R.id.tab_content, cardFragment).add(R.id.tab_content, mineFragment).hide(cardFragment).hide(mineFragment).show(homeFragment)
                .commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showExceptionDialogFromIntent(intent);

    }

    private void showExceptionDialogFromIntent(Intent intent) {
        EMLog.e(TAG, "showExceptionDialogFromIntent");
        if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)) {
            showExceptionDialog(Constant.ACCOUNT_CONFLICT);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false)) {
            showExceptionDialog(Constant.ACCOUNT_REMOVED);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_FORBIDDEN, false)) {
            showExceptionDialog(Constant.ACCOUNT_FORBIDDEN);
        }
    }

    /**
     * show the dialog when user met some exception: such as login on another device, user removed or user forbidden
     */
    private void showExceptionDialog(String exceptionType) {
        isExceptionDialogShow = true;
        String str = getResources().getString(R.string.Logoff_notification);// 下线通知
        DemoHelper.getInstance().logout(false, null);
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_logout_dialog_xml, R.style.Theme_dialog);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        tv_title.setText(str);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        tv_content.setText(getExceptionMessageId(exceptionType));

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!MainActivity.this.isFinishing()) {
                    isExceptionDialogShow = false;
                    logout();
                    dialog.dismiss();
                }
            }
        });
        isConflict = true;
        dialog.setCancelable(false);
        dialog.show();
    }

    private int getExceptionMessageId(String exceptionType) {
        if (exceptionType.equals(Constant.ACCOUNT_CONFLICT)) {
            return R.string.connect_conflict;
        } else if (exceptionType.equals(Constant.ACCOUNT_REMOVED)) {
            return R.string.em_user_remove;
        } else if (exceptionType.equals(Constant.ACCOUNT_FORBIDDEN)) {
            return R.string.user_forbidden;
        }
        return R.string.Network_error;
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void getCountrySuccess(Country model) {
        try {
            if (model != null) {
                if (model.getStatus() == HttpUtil.RESULT_OK) {
                    List<Country.DataBean> data = model.getData();
                    // 保存国家到本地
                    if (data != null && data.size() > 0) {
                        placeDB.savePlaceList(data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {

    }

    public class MyContactListener implements EMContactListener {
        @Override
        public void onContactAdded(String username) {
        }

        @Override
        public void onContactDeleted(final String username) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null &&
                            username.equals(ChatActivity.activityInstance.toChatUsername)) {
                        String st10 = getResources().getString(R.string.have_you_removed);
                        Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                .show();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });
        }

        @Override
        public void onContactInvited(String username, String reason) {
        }

        @Override
        public void onContactAgreed(String username) {
        }

        @Override
        public void onContactRefused(String username) {
        }
    }

    /**
     * debug purpose only, you can ignore this
     */
    private void registerInternalDebugReceiver() {
        internalDebugReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                DemoHelper.getInstance().logout(false, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                logout();
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(int code, String message) {
                    }
                });
            }
        };
        IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
        registerReceiver(internalDebugReceiver, filter);
    }


    /**
     * 初始化控件
     */
    private void initViews() {
//        mTabs = new TextView[5];
        views = new ImageView[5];
        views[0] = iv_home;
        views[1] = ivCategory;
        views[2] = ivFind;
        views[3] = ivShop;
        views[4] = ivMine;

//        mTabs[0] = (TextView) findViewById(R.id.tv_home);
//        mTabs[1] = (TextView) findViewById(R.id.tv_category);
//        mTabs[2] = (TextView) findViewById(R.id.tv_find);
//        mTabs[3] = (TextView) findViewById(R.id.tv_shop);
//        mTabs[4] = (TextView) findViewById(R.id.tv_me);
//        // 把第一个tab设为选中状态
//        mTabs[0].setSelected(true);
        views[0].setSelected(true);
    }

    @OnClick({R.id.ll_container_home, R.id.ll_container_category, R.id.ll_container_find, R.id.ll_container_shop, R.id.rl_container_me})
    public void onClick(View view) {
        if (Tools.Utils.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_container_home:
                index = 0;
                break;
            case R.id.ll_container_category:
                index = 1;
                break;
            case R.id.ll_container_find:
                index = 2;
                break;
            case R.id.ll_container_shop:
                index = 3;
                break;
            case R.id.rl_container_me:
                index = 4;
                break;
        }
        if (currentTabIndex != index) {
            // 如果用户名密码都有，直接进入主页面
            if (index == 3 || index == 4) {
                if (!isCheckedLogin()) {
                    startAct(LoginActivity.class);
                    return;
                }
            }
            FragmentTransaction trx = obtainFragmentTransaction(index);
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.tab_content, fragments[index]);
            }
            trx.show(fragments[index]).commit();
//            mTabs[currentTabIndex].setSelected(false);
            views[currentTabIndex].setSelected(false);
            // 把当前tab设为选中状态
//            mTabs[index].setSelected(true);
            views[index].setSelected(true);
            currentTabIndex = index;
        }
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // 设置切换动画,如果当前项不是选中项就启动动画切换
        if (index > currentTabIndex) {
            ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
        } else {
            ft.setCustomAnimations(R.anim.slide_right_in,
                    R.anim.slide_right_out);
        }
        return ft;
    }


    /**
     * @return boolean 返回类型
     * @Title: inFirst
     * @Description: 只有回到首页按才能退出应用
     * @author lmw
     */
    public boolean inFirst() {
        if (currentTabIndex == 0) {
            return true;
        }
        return false;
    }

    /**
     * @return void 返回类型
     * @Title: openFirst
     * @Description: 按返回键退出时如果不是首页，就先回到首页在退出
     * @author lmw
     */
    public void openFirst() {
        if (currentTabIndex != 0) {
            currentTabIndex = 0;
        }
        Fragment fragment = fragments[currentTabIndex];
        FragmentTransaction ft = obtainFragmentTransaction(currentTabIndex);
        getCurrentFragment().onPause(); // 暂停当前tab
        if (fragment.isAdded()) {
            onCheckedIndex(currentTabIndex);
            fragment.onResume(); // 启动目标tab的onResume()
        } else {
            // 将Fragment替换在指定的区域
            ft.add(R.id.tab_content, fragment);
        }
        showTab(currentTabIndex); // 显示目标tab
        ft.commit();
    }

    /**
     * 切换tab
     *
     * @param idx
     */
    private void showTab(int idx) {
        for (int i = 0; i < fragments.length; i++) {
            Fragment fragment = fragments[i];
            FragmentTransaction ft = obtainFragmentTransaction(idx);
            // 传来的下标显示相应的页面，其他的则隐藏
            if (idx == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
            // 一定要提交
            ft.commitAllowingStateLoss();
        }
        currentTabIndex = idx; // 更新目标tab为当前tab
    }

    /**
     * @param currentTab
     * @return void 返回类型
     * @Title: onCheckedIndex
     * @Description: 返回主页面时显示哪项被选中
     * @author lmw
     */
    public void onCheckedIndex(int currentTab) {
        for (int i = 0; i < views.length; i++) {
//            mTabs[i].setSelected(false);
            views[i].setSelected(false);
        }
//        mTabs[currentTab].setSelected(true);
        views[currentTab].setSelected(true);
    }

    /**
     * 返回选中的Fragment
     */
    public Fragment getCurrentFragment() {
        return fragments[currentTabIndex];
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 登录过才操作
        if (isCheckedLogin()) {
            if (!isConflict && !isCurrentAccountRemoved) {
                updateUnreadLabel();
            }
            // unregister this event listener when this activity enters the
            // background
            DemoHelper sdkHelper = DemoHelper.getInstance();
            sdkHelper.pushActivity(this);
            EMClient.getInstance().chatManager().addMessageListener(messageListener);
        } else {
            unreadMsgNumber.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    protected void onStop() {
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.popActivity(this);
        super.onStop();
    }

    /**
     * 注册消息监听
     */
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
            }
        });
    }

    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        int messagesCount = messageDB.getByAllMessagesCount();
        if (count > 0 || messagesCount > 0) {
            // 有聊天消息，也显示右上角红点图标
            if (homeFragment != null) {
                homeFragment.initMessage(count);
            }
            if (mineFragment != null) {
                mineFragment.initMessage();
            }
            if ((count + messagesCount) > 99) {
                unreadMsgNumber.setText("99+");
            } else {
                unreadMsgNumber.setText(String.valueOf(count + messagesCount));
            }
            unreadMsgNumber.setVisibility(View.VISIBLE);
        } else {
            unreadMsgNumber.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * get unread message count
     * 获取未读消息数量
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }

        if (mLocClient != null) {
            mLocClient.stop();
        }

        isExceptionDialogShow = false;
        unregisterBroadcastReceiver();
        try {
            unregisterReceiver(internalDebugReceiver);
        } catch (Exception e) {
        }
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    private long eventTime = 0l;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                if (inFirst()) {
                    long eventT = event.getEventTime();
                    if (eventT - eventTime < 2000l) {
                        moveTaskToBack(false);
                        finish();
                        return false;
                    }
                    showToast("再按一次退出程序");
                    eventTime = eventT;
                } else {
                    openFirst();
                }

                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 注销登录
     */
    public void logout() {
        DemoHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        isExceptionDialogShow = false;
                        startAct(LoginActivity.class);
                        App.getInstance().saveObject(null, HttpUtil.USER_KEY);
                        if (currentTabIndex == 3 || currentTabIndex == 4) {
                            showTab(0);
                            onCheckedIndex(0);
                        }
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(int code, String message) {
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    /**
     * 定位
     */
    private void showMapWithLocationClient() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// open gps
        // option.setCoorType("bd09ll");
        // Johnson change to use gcj02 coordination. chinese national standard
        // so need to conver to bd09 everytime when draw on baidu map
        option.setCoorType("gcj02");
        option.setAddrType("all");
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * format new location to string and show on screen
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            lastLocation = location;
            String name = lastLocation.getAddress().province;// 得到定位省份
            if (!Tools.isNull(name) && name.endsWith("市")) {
                name = name.replaceAll("市", "");
            } else if (!Tools.isNull(name) && name.endsWith("省")) {
                name = name.replaceAll("省", "");
            }
            String byId = findDB.getProvinceById(name);
            SharedPreferencesUtil.saveData(MainActivity.this, HttpUtil.P_ID, byId);
            SharedPreferencesUtil.saveData(MainActivity.this, HttpUtil.P_NAME, name);
            if (homeFragment != null) {
                homeFragment.initCity();
            }
            T.showToast(mContext, "定位");
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }
}
